#pragma once
#include <iostream>
#include "Socket.hpp"

//该类未来统一进行listensockfd的管理工作，获取新连接
using namespace socket_ns;

class Listener
{
public:
    Listener(uint16_t port):_port(port),_listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildListenSocket(port);
    }
    int ListenSockfd()
    {
        return _listensock->Sockfd();
    }
    void Accepter(Connection* conn)
    {
        while(true)
        {
            errno = 0;  
            InetAddr addr;
            int code = 0;
            int sockfd = _listensock->Accepter(&addr, &code);  
            if(sockfd > 0)
            {
                LOG(INFO, "获取连接成功，客户端：%s:%d, sockfd:%d\n", addr.Ip().c_str(), addr.Port(), sockfd);
                conn->_R->AddConnection(sockfd, EPOLLIN|EPOLLET, addr, NormalConnection);
            }
            else
            {
                if(code == EWOULDBLOCK)
                {
                    LOG(INFO, "底层连接全部获取完毕");
                    break;
                }
                else if(code == EINTR)
                {
                    continue;
                }
                else
                {
                    LOG(ERROR, "获取连接失败！\n");
                    break;
                }
            }
        }
        
    }
    ~Listener(){}

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensock;
};